import numpy as np
from scipy.sparse import csr_matrix
import scipy.sparse
import scipy.linalg
import scipy.io as scio

import time

# 测试简单矩阵迭代法时间、直接运算时间
# 1、普通矩阵迭代法Ax=b-> x=(E+F)x+b
#x=np.matrix([0,0,0]).T
#A = np.matrix([[8 ,-3, 2],[4, 11, -1],[6,3,12]])
#b = np.matrix([1,2,2]).T

A = np.random.rand(50,50)
n = A.shape[0]
b = np.random.rand(n,1)
x = np.random.rand(n,1)

F = -np.triu(A,1)
E = -np.tril(A,-1)
D = A + F + E

start=time.time()
for i in range(10):
    x=np.linalg.inv(D-E).dot((F).dot(x)+b)
print(x)
end=time.time()
print (end-start)

# 直接计算
x2 = np.matrix([0,0,0]).T
start=time.time()
x2 = np.linalg.inv(A).dot(b)
end=time.time()
print(x2)
print(end-start)

'''
# 2、稀疏矩阵求逆

#A = csr_matrix(A)
dataFile = '../ibmpg/ibmpg1.mat'
data = scio.loadmat(dataFile)
A = data['G']

n = A.shape[0]
B = scipy.sparse.rand(n,1,1)
iteration_num = 30

for k in range(iteration_num):
    x2 = scipy.linalg.inv(D-E).dot(F.dot(x)+b)

#import matplotlib.pyplot as plt
#plt.imshow(A,cmap = 'hot')
#plt.axis('off')
#plt.show()
'''
